import {computed, createStore, delay, designComponent, onMounted, PropType, reactive, useClasses, watch} from "@peryl/react-compose";
import {AppMenu} from "../components/AppMenu";
import {AppHeader} from "../components/AppHeader";
import {i18n} from "plain-design";
import {MicroList} from "../components/MicroList";
import {microApp} from "../microApp";
import CrmLocale from './Crm.locale';
import {env} from "../env";
import {MenuGroups} from "../menus";
import {iMicroTokenInfo} from "@peryl/micro-web";
import {useCurrentMicroConfig} from "../components/useCurrentMicroConfig";

i18n.setLangs(CrmLocale);
console.log({ i18n });

export const Crm = designComponent({
  props: {
    init: { type: Function as PropType<() => Promise<iMicroTokenInfo>> },
  },
  setup({ props }) {

    const menuStore = createStore({
      getCacheConfig: () => ({
        envName: env.envName,
        cacheName: '@@APP_MENU'
      }),
      initialState: {
        menuSize: 225,
        menuCollapse: false
      }
    });

    const state = reactive({ ...menuStore.value, tokenInfo: null as null | iMicroTokenInfo, isMounted: false, });

    delay(23).then(() => state.isMounted = true);

    const cssStyles = computed(() => `.app-container .app-home{--app-menu:${state.menuCollapse ? 40 : state.menuSize}px;}`);

    const classes = useClasses(() => [
      'app-home',
      {
        'app-home-collapse-menu': state.menuCollapse,
        'app-home-collapse-menu-not-mounted': !state.isMounted
      }
    ]);

    watch(() => [state.menuCollapse, state.menuSize], () => {menuStore.value = { ...state };});

    if (!!props.init) {
      props.init().then(tokenInfo => {
        state.tokenInfo = tokenInfo;
      });
    } else {
      window.history.replaceState({}, '', microApp.route.buildMicroPublicPath());
      onMounted(async () => {
        try {
          /*先检查登录有效性*/
          const tokenInfo = await microApp.config.getToken();
          /*应用缓存*/
          microApp.cache.apply({
            route: 'crm',
            handleNoCache: () => {
              /*没有缓存的情况下，打开首页*/
              MenuGroups.openHomePage();
            },
            handleApplied: async () => {
              /*先检查登录有效性*/
              state.tokenInfo = tokenInfo;
            },
          });
        } catch (e) {
          microApp.login.logout();
        }
      });
    }

    const currentMicroConfig = useCurrentMicroConfig.provide();

    return () => (
      !!state.tokenInfo && <div className={classes.value}>
        <style>{cssStyles.value}</style>
        <AppMenu v-model:size={state.menuSize} v-model:collapse={state.menuCollapse}/>
        <AppHeader/>
        <div
          className="app-content"
          data-current-micro={currentMicroConfig.state.current?.microConfig.id || '_'}
          data-current-frame-mode={currentMicroConfig.state.current?.frameMode || '_'}
          data-current-render-mode={currentMicroConfig.state.current?.renderMode || '_'}
        >
          <div className="app-content-inner">
            <MicroList tokenInfo={state.tokenInfo}/>
          </div>
        </div>
      </div>
    );
  },
});
